Page({
  data: {
    questions: [],
    currentIndex: 0,
    showExplanation: false,
    userAnswer: '',
    showResult: false,
    correctCount: 0,
    isLoading: false // 防止重复请求
  },

  onLoad(options) {
    const bankId = options.bankId || 1390; // 支持URL传参
    this.fetchQuestions(bankId);
  },

  // 优化的请求方法（带防抖/错误处理）
  fetchQuestions(bankId) {
    if (this.data.isLoading) return; // 防止重复点击
    this.setData({ isLoading: true });
  
    wx.showLoading({ title: '加载题目中...', mask: true });
  
    wx.request({
      url: `http://47.119.146.254:8084/question/bank/${bankId}/1/20`,
      method: 'GET',
      timeout: 10000, // 10秒超时
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        console.log('[题库接口响应]', res);
  
        if (res.statusCode !== 200 || !res.data || !res.data.data) {
          return wx.showToast({ title: '加载失败，请检查服务器', icon: 'none' });
        }
  
        const { data } = res.data;
  
        this.setData({
          questions: data.list.map(q => ({
            questionId: q.questionId,
            content: (q.content || '').replace(/\$/g, ''), // 处理 LaTeX 公式
            explanation: (q.explanation || '').replace(/\n/g, '<br>'), // 处理换行
            answer: q.answer, // 正确答案
            bankId: q.bankId,
            optionsArray: [
              { key: 'A', text: q.a.replace(/\$/g, '') },
              { key: 'B', text: q.b.replace(/\$/g, '') },
              { key: 'C', text: q.c.replace(/\$/g, '') },
              { key: 'D', text: q.d.replace(/\$/g, '') }
            ]
          })),
          total: data.total
        });
      },
      fail: (err) => {
        console.error('[网络错误]', err);
        wx.showToast({ title: '网络请求失败，请检查网络', icon: 'none', duration: 2000 });
      },
      complete: () => {
        this.setData({ isLoading: false });
        wx.hideLoading();
      }
    });
  },

  onSelect(e) {
    const { value } = e.detail;
    const currentQuestion = this.data.questions[this.data.currentIndex];
    
    this.setData({
      userAnswer: value,
      showResult: true,
      // 自动展开解析
      showExplanation: true
    });

    // 统计正确率
    if (value === currentQuestion.answer) {
      this.setData({ correctCount: this.data.correctCount + 1 });
    }
  },

  toggleExplanation() {
    this.setData({ showExplanation: !this.data.showExplanation });
  },

  nextQuestion() {
    const nextIndex = this.data.currentIndex + 1;
    this.setData({
      currentIndex: nextIndex,
      showResult: false,   // 进入下一题时隐藏答案
      showExplanation: false, // 进入下一题时隐藏解析
      userAnswer: ''  // 清空上一个答案
    });
  },

  finishPractice() {
    wx.showModal({
      title: '练习完成',
      content: `共${this.data.questions.length}题，答对${this.data.correctCount}题\n正确率：${((this.data.correctCount / this.data.questions.length) * 100).toFixed(1)}%`,
      success: (res) => {
        if (res.confirm) {
          wx.navigateBack();
        }
      }
    });
  },

  // 新增：下拉刷新
  onPullDownRefresh() {
    this.fetchQuestions(this.data.questions[0]?.bankId || 1390);
    wx.stopPullDownRefresh();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
});